<?php

namespace App\Http\Controllers\admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

use DB;
class UsersController extends Controller
{
    public function index (Request $request) 
    {	
        $where = [];
        // dd($where);
    	//实例化要操作的表
    	$db = DB::table('users');
        // dd($request);
        if($request->has('keywords')){
            $name = $request->input('keywords');
            // dd($name);
            $db->where('username','like',"%{$name}%");

            $where['username'] = $name;
        };    	
        // dd($where);
        // 分页
    	$list = $db->paginate(5);
    	//加载模板
    	return view('admin.user.userlist',['list'=>$list,'where'=>$where]);
    }
    public function create() 
    {
    	return view('admin.user.useradd');
    }
    public function store(Request $request)
    {
    	$messages = [
    		'required' => ':attribute 的字段是必要的',
    	];
    	//
    	$this->validate($request, [
	        'username' => 'required|unique:users|max:16',
	        'password' => 'required|unique:users|max:16',
            'email' => 'required|unique:users|max:16|min:6',
	    ],$messages);
    	$name = $request->except('_token','password','newpassword');
        //获取input表单密码
        $password = $request->input('password');
        //获取表单确认密码
        $newpassword = $request->input('newpassword');
        // 判断密码是否一致
        if($password == $newpassword){
            $name['password'] = md5($password);
            $list = DB::table('users')->insertGetId($name);
            // dd($list);
            if($list>0) {
            return redirect('admin/userlist')->with('msg','添加成功');
            }
        }else{
            return redirect('admin/userlist')->with('msg','两次密码不匹配，添加失败请重新添加！');
            // return 123;
        }
    	
    	 
    }
    public function destroy ($id)
    {

    	$list = DB::table('users')->where('id',$id)->delete();
    	if($list>0){
    		return redirect('admin/userlist');
    	}
    }
    public function edit($id)
    {
    	$list = DB::table('users')->where('id',$id)->first();
        // dd($list);
    	return view('admin.user.useredit',['list'=>$list]);
    }

    public function update($id,Request $request)
    {
    	// dd($request);
    	$name = $request->except("_token","_method");
    	// dd($request);
    	$list = DB::table('users')->where('id',$id)->update($name);
         // dd($list);
    	if($list>0){
    		return redirect('admin/userlist')->with('msg','修改成功');
    	}

    }

}
